package com.efrei.uchat.message;

import com.efrei.uchat.exception.UChatException;

/**
 * Login query Message
 * format: #sessionid#LOGIN#mylogin#
 * mylogin will be attached at sessionid
 * @author pierrick
 */
public class LoginMessage extends SystemMessage {
	
	private String login;
	private int status = 0;
	
	public LoginMessage(String text) throws UChatException {
		super(text);
		updateFromFields();
	}
	
	public LoginMessage(String login, int sessionId) {
		super(Headers.LOGIN, sessionId);
		// update fields
		this.fields.add(login);
		// and attribute
		updateFromFields();
	}
	
	private void updateFromFields() {
		this.login = fields.get(0);
		if(fields.size()==2) {
			this.status = fields.get(1).equals("ok")?1:2;
		} else {
			this.status = 0;
		}
	}
	
	public String getLogin() {
		return login;
	}
	
	public Boolean isValid() {
		switch (status) {
		case 1:
			return true;
		case 2:
			return false;
		default:
			return null;
		}
	}
	
	protected void setStatus(int status) {
		switch(status) {
		case 0:
			if(this.status!=status) {
				fields.remove(0);
			}
			break;
		case 1:
		case 2:
			String t = (status==1?"ok":"err");
			if(this.status==0) {
				fields.add(1, t);
			} else {
				fields.set(1, t);
			}
			break;
		default:
			return;
		}
		this.status = status;
	}
	
	/*
	 * message's answers
	 */
	
	public LoginMessage returnAnswer(boolean isValid) throws UChatException {
		LoginMessage msg = new LoginMessage(this.toString());
		msg.setStatus( (isValid?1:2) );
		return msg;
	}
}
